package com.lizhaoshan.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.lizhaoshan.dao.CategoryDao;
import com.lizhaoshan.dto.CategoryDto;
import com.lizhaoshan.pojo.Category;
import com.lizhaoshan.pojo.PageBean;
import com.lizhaoshan.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * @program: reggie
 * @description:
 * @author: lamour
 * @create: 2022-05-14 19:30
 **/
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public boolean addCategory(CategoryDto categoryDto) {

        //设置id
        // String newId = IdWorker.getIdStr();
        // categoryDto.setId(newId);


        String id = new Snowflake().nextIdStr();
        categoryDto.setId(id);


        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String format = dtf.format(LocalDateTime.now());
        categoryDto.setUpdateTime(format);
        categoryDto.setCreateTime(format);
        // String employeeId = TokenHolder.getCurrentId();
        categoryDto.setCreateUser(id);
        categoryDto.setUpdateUser(id);
        Category category = new Category();
        Category selectByNameCategory = categoryDao.selectByNameCategory(category);
        if (selectByNameCategory == null){
            BeanUtils.copyProperties(categoryDto, category);
            return categoryDao.addCategory(category) > 0;
        }else {
            return false;
        }

    }

    @Override
    public boolean putCategory(CategoryDto categoryDto) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDto, category);
        return categoryDao.updateCategory(category) > 0 ;
    }

    @Override
    public boolean deleteCategory(String id) {
        return categoryDao.deleteCategory(id) > 0 ;
    }

    @Override
    public List<Category> getCategoryType(Integer type) {
        return categoryDao.selectAllByType(type);
    }

    @Override
    public PageBean<Category> getCategoryPages(Integer page, Integer pageSize) {
        int begin = (page - 1) * pageSize;
        // int size = pageSize;

        List<Category> categories = categoryDao.selectPage(begin, pageSize);
        int pageCount = categoryDao.pageCount(begin, pageSize);

        PageBean<Category> pageBean = new PageBean<>();
        pageBean.setTotal(pageCount);
        pageBean.setRecords(categories);

        return pageBean;
    }


}
